﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using H2.Streams;

namespace Mystery.SCNR.Scripts
{
    public class ScriptFunction
    {
        public const int Offset = 440;
        public const int ChunkSize = 40;

        public string Name;

        public FunctionTypes Type;

        public VariableTypes ReturnType;

        public short SyntaxChunkNumber;
        public ushort RootExpressionIndex;

        public string GetName()
        { 
            return Name.TrimEnd('\0'); 
        }

        public override string ToString()
        {
            return GetName();
        }

        public static ScriptFunction[] Read(MapStream map, int scnrOffset)
        {
            ScriptFunction[] scriptFunctions = new ScriptFunction[map.ReadReflexiveAt(scnrOffset + Offset)];

            for (int i = 0; i < scriptFunctions.Length; i++)
            {
                ScriptFunction sf = new ScriptFunction();
                scriptFunctions[i] = sf;

                sf.Name = map.ReadString(32, false);
                sf.Type = (FunctionTypes)map.ReadInt16();
                sf.ReturnType = (VariableTypes)map.ReadInt16();
                sf.SyntaxChunkNumber = map.ReadInt16();
                sf.RootExpressionIndex = map.ReadUInt16();
            }

            return scriptFunctions;
        }

        public static void Write(MapStream map, int scnrOffset, ScriptFunction[] scriptFunctions)
        {
            map.ReadReflexiveAt(scnrOffset + Offset);

            for (int i = 0; i < scriptFunctions.Length; i++)
            {
                ScriptFunction sf = scriptFunctions[i];

                map.Write(sf.Name);
                map.Write((short)sf.Type);
                map.Write((short)sf.ReturnType);
                map.Write(sf.SyntaxChunkNumber);
                map.Write(sf.RootExpressionIndex);
            }
        }
    }
}
